package com.app.android.coliy.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;

import com.app.android.coliy.R;
import com.app.android.coliy.bean.VoiceResultBean;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.util.AnimUtil;
import com.app.android.coliy.util.Util;
import com.google.gson.Gson;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

/**
 * Created by Administrator on 2018/8/29.
 */

public class Voice_Dialog extends Dialog implements View.OnClickListener {
    public Voice_Dialog(@NonNull Context context) {
        super(context, R.style.myDialog);
    }

    public Voice_Dialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    protected Voice_Dialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    LinearLayout ll_content;
    View view_bg;
    TextView tv_text;

    CommCallBack callBack;

    //设置输入回调
    public void setIntputCallBack(CommCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_voice);
        initView();
        startVoice();
    }

    private void initView() {
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        view_bg = findViewById(R.id.view_bg);

        view_bg.setOnClickListener(this);
        ll_content.setOnClickListener(this);

        AnimUtil.fadeIn(view_bg);
        AnimUtil.fadeIn(ll_content);

        tv_text = findViewById(R.id.tv_text);
    }


    private void startVoice() {
        //初始化识别无UI识别对象
        //使用SpeechRecognizer对象，可根据回调消息自定义界面；
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(getContext(), new InitListener() {
            @Override
            public void onInit(int i) {
                Log.i("onInit:" + i);
            }
        });

        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
        mIat.setParameter(SpeechConstant.SUBJECT, null);
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        //此处engineType为“cloud”
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        //设置语音输入语言，zh_cn为简体中文
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        //设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");
        //开始识别，并设置监听器
        mIat.startListening(new RecognizerListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {
            }

            @Override
            public void onBeginOfSpeech() {
                Log.i("onBeginOfSpeech:");
                tv_text.setText(Util.getString(R.string.edit_voice_reading));
            }

            @Override
            public void onEndOfSpeech() {
                Log.i("onEndOfSpeech:");
                tv_text.setText(Util.getString(R.string.edit_voice_end));
            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                Log.i("recognizerResult:" + recognizerResult.getResultString());
                try {
                    String result = "";
                    VoiceResultBean voiceResultBean = new Gson().fromJson(recognizerResult.getResultString(), VoiceResultBean.class);
                    if (!voiceResultBean.ls) {
                        for (int i = 0; i < voiceResultBean.ws.size(); i++) {
                            for (int k = 0; k < voiceResultBean.ws.get(i).cw.size(); k++) {
                                String text = voiceResultBean.ws.get(i).cw.get(k).w;
                                result += text;
                            }
                        }
                        if (!TextUtils.isEmpty(result)) {
                            result = result.replace("。","");
                            if (callBack != null) {
                                callBack.onResult(result);
                                dismissWithAnim();
                            }
                        } else {
                            CommToast.showToast(getContext(), Util.getString(R.string.edit_voice_reading_fail));
                            dismissWithAnim();
                        }
                        Log.i("result:" + result);
                    }
                    else
                    {
//                        CommToast.showToast(getContext(), Util.getString(R.string.edit_voice_reading_fail));
                        dismissWithAnim();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(SpeechError speechError) {
                Log.i("onError:" + speechError.getErrorDescription());
                CommToast.showToast(getContext(),getContext().getString(R.string.edit_voice_error));
                dismissWithAnim();
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
                Log.i("onEvent:" + i);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_bg:
                dismissWithAnim();
                break;
            case R.id.ll_content:
                //不处理，只消耗点击事件
                break;
        }
    }

    public void dismissWithAnim() {
        if (view_bg.getAnimation() != null) return;
        AnimUtil.fadeOut(ll_content, null);
        AnimUtil.fadeOut(view_bg, new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                dismiss();
            }
        });
    }

    @Override
    public void onBackPressed() {
        dismissWithAnim();
    }
}
